import Vue from 'vue'
import Vuex from 'vuex'
import { setItem, getItem, removeItem } from '@/utils/storage'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // takenInfo 代表的是请求回来的token对象
    tokenInfo: getItem('tokenInfo') || {},
    // 个人信息
    userInfo: getItem('userInfo') || {}
  },
  mutations: {
    // 获取登陆后请求回来的token值
    mSetToken (state, tokenObj) {
      state.tokenInfo = tokenObj
      // 将token数据保存到本地
      setItem('tokenInfo', tokenObj)
    },
    mClearTokenInfo (state) {
      // 保存到vuex
      state.tokenInfo = {}
      // 持久化到本地
      removeItem('tokenInfo')
    },
    mUpdateName (state, newName) {
      state.userInfo.name = newName

      setItem('userInfo', state.userInfo)
    },
    mUpdateGender (state, newGender) {
      state.userInfo.gender = newGender

      setItem('userInfo', state.userInfo)
    },
    mUpdateBirthday (state, newBirthday) {
      state.userInfo.birthday = newBirthday

      setItem('userInfo', state.userInfo)
    },
    mUpdatePhoto (state, newPhoto) {
      state.userInfo.photo = newPhoto

      setItem('userInfo', state.userInfo)
    },
    mSetUserInfo (state, userInfo) {
      state.userInfo.birthday = userInfo.birthday
      state.userInfo.gender = userInfo.gender
      state.userInfo.id = userInfo.id.toString()
      state.userInfo.mobile = userInfo.mobile
      state.userInfo.name = userInfo.name
      state.userInfo.photo = userInfo.photo
      setItem('userInfo', state.userInfo)
    }

  },
  // getters 相当于计算属性
  // 基于state众多的数据产生新的数据项
  // 他就是一个函数 他会接受state 作为第一个参数
  getters: {
    // 是否登录了
    isLogin (state) {
      if (state.tokenInfo.token) {
        return true
      } else {
        return false
      }
    },
    // 获取用户头像
    userPhoto (state) {
      return state.userInfo.photo
    }
  }
})
